﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NetUtil  
{
    static NetUtil instance_;
    public static NetUtil instance
    {
        get
        {
            if (instance_ == null)
            {
                instance_ = new NetUtil();
            }
            return instance_;
        }
    }

    public void Request(string url, Action<WWW> back,Action timeOutAction)
    {
        rdl.Add(new ReqData(url, back, timeOutAction));
    }

    List<ReqData> rdl = new List<ReqData>();

    public void Update()
    {
        for (int i = rdl.Count-1; i >=0; i--)
        {
            ReqData rd = rdl[i];
            if (rd.isDone)
            {
                rd.Finish();
                rdl.RemoveAt(i);
            } else
            {
                rd.timeOut -= Time.deltaTime;
                if (rd.timeOut < 0)
                {
                    rd.TimeOut();
                    rdl.RemoveAt(i);
                }
            }
        }
    }

}
class ReqData
{
    public ReqData()
    {

    }
    public ReqData(string urlPath,Action<WWW> back,Action timeBack = null, float time = 5f)
    {
        url = urlPath;
        string reqUrl = urlPath + GetRanomPrefix();
        w = new WWW(reqUrl);
        timeOut = time;
        this.back = back;
        timeOutAction = timeBack;
    }
    string url;
    string GetRanomPrefix()
    {
        return "?"+"random="+UnityEngine.Random.Range(1,int.MaxValue)+"";
    }
    public bool isDone
    {
        get
        {
            return w.isDone;
        }
    }
    WWW w;
    public Action<WWW> back;
    Action timeOutAction;
    public float timeOut;
    public void Finish()
    {
        if (w != null)
        {
            if (back != null)
            {
                back(w);
            }
        }
        else
        {
            if (back != null)
            {
                back(null);
            }
        }
    }

    public void TimeOut()
    {
        if (timeOutAction != null)
        {
            timeOutAction();
        }
    }
}